package model;

import global.Global;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import ui.ServerWindow;
import control.ServerConnector;

public class Server {
	
	private ServerSocket serverSocket;
	private ServerWindow serverWindow; 
	
	public void start() throws IOException {
		this.serverSocket = new ServerSocket(Global.PORT);

		this.serverWindow = new ServerWindow(new CloseAction(), "Log");
		serverWindow.show();

		while(true) {
			try {
				if(!serverSocket.isClosed()) {
					Socket socket = this.serverSocket.accept();
					ServerConnector sc = new ServerConnector(socket, new WriteListener());
					new Thread(sc).start();
				}
			} catch(SocketException e) {
				break;
			}
		}
	}
	
	public void close() {
		try {
			serverSocket.close();
			ServerConnector.endAll();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class CloseAction {
		public void closeServer() {
			close();
		}
	}
	
	public class WriteListener {
		public void writeMessage(String message) {
			serverWindow.showMessage(message);
		}
	}
}
